package com.hetwen.search.demo.view;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.hetwen.search.demo.R;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by android on 2016/1/5 0005.
 */
public class BannerView extends RelativeLayout implements ViewPager.OnPageChangeListener {

    private ViewPager pager;
    private BannerAdapter adapter;
    private LinearLayout wrapper;

    private int size;

    private List<RadioButton> dots;

    private List<ImageView> views;

    private int currentPage = Integer.MAX_VALUE / 2;

    private BannerHandler handler;

    private int delay = 3000;

    private OnBannerClickListener listener;

    public BannerView(Context context) {
        super(context);
        initView(context);
    }

    public BannerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public BannerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    /**
     * 加载布局文件
     */
    private void initView(Context context) {
        handler = new BannerHandler(this);
        views = new ArrayList<>();
        dots = new ArrayList<>();
        RelativeLayout layout = new RelativeLayout(context);
        LayoutParams params = new LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT
        );
        layout.setLayoutParams(params);

        pager = new ViewPager(context);
        LayoutParams params1 = new LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT
        );
        pager.setLayoutParams(params1);
        pager.addOnPageChangeListener(this);

        wrapper = new LinearLayout(context);
        LayoutParams params2 = new LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT
        );
        params2.addRule(ALIGN_PARENT_BOTTOM);
        params2.setMargins(0, 0, 0, 8);
        wrapper.setLayoutParams(params2);
        wrapper.setOrientation(LinearLayout.HORIZONTAL);
        wrapper.setGravity(Gravity.CENTER);

        layout.addView(pager);
        layout.addView(wrapper);

        addView(layout);
    }


    public void refreshBanner(List<String> banners) {
        if (banners == null) {
            throw new RuntimeException("views must not be null");
        }
        size = banners.size();
        refreshViews(banners);
        refreshDots();
        if (adapter == null) {
            adapter = new BannerAdapter(views);
            pager.setAdapter(adapter);
            pager.setCurrentItem(currentPage, false);
            handler.sendEmptyMessageDelayed(0, delay);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    private void refreshViews(List<String> banners) {
        views.clear();
        for (int i = 0; i < size; i++) {
            ImageView imageView = new ImageView(getContext());
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setClickable(true);
            Glide.with(getContext()).load(banners.get(i)).into(imageView);
            final int j = i;
            imageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        listener.onClick(j);
                    }
                }
            });
            views.add(imageView);
        }
    }

    private void refreshDots() {
        wrapper.removeAllViews();
        dots.clear();
        for (int i = 0; i < size; i++) {
            RadioButton dot = new RadioButton(getContext());
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            if (Build.VERSION.SDK_INT < 11) {
                layoutParams.setMargins(-20, 0, -20, 0);
            }
            dot.setLayoutParams(layoutParams);
            dot.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
            dot.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.selector_dot);
            dot.setPadding(5, 0, 5, 0);
            dot.setVisibility(View.VISIBLE);
            if (i == currentPage % size) {
                dot.setChecked(true);
            } else {
                dot.setChecked(false);
            }
            dot.setClickable(false);
            wrapper.addView(dot);
            dots.add(dot);
        }
    }

    public void setDelay(int delay) {
        this.delay = delay;
    }

    public void setBannerListener(OnBannerClickListener listener) {
        this.listener = listener;
    }

    /**
     * 切换
     */
    private void switchItem() {
        if (!views.isEmpty()) {
            pager.setCurrentItem(currentPage + 1);
            handler.sendEmptyMessageDelayed(0, delay);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        int lastPage = currentPage;
        currentPage = position;
        dots.get(lastPage % size).setChecked(false);
        dots.get(currentPage % size).setChecked(true);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    private class BannerAdapter extends PagerAdapter {

        private List<ImageView> list;

        public BannerAdapter(List<ImageView> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView imageView = list.get(position % size);
            ViewGroup parent = (ViewGroup) imageView.getParent();
            if (parent != null) {
                parent.removeAllViews();
            }
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    }

    private static class BannerHandler extends Handler {

        private WeakReference<BannerView> weakref;

        public BannerHandler(BannerView view) {
            this.weakref = new WeakReference<>(view);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                BannerView view = weakref.get();
                if (view != null) {
                    view.switchItem();
                }
            }
        }
    }

    public interface OnBannerClickListener {
        void onClick(int i);
    }
}
